package cn.edu.zut.soft.graduate.controller.stu;

import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.graduate.controller.BaseController;
import cn.edu.zut.soft.graduate.core.constant.InviteStatus;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.model.Impl.CreateGroup;
import cn.edu.zut.soft.graduate.core.model.Impl.Group;
import cn.edu.zut.soft.graduate.core.query.IdentityQuery;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.core.vo.UserDescVO;
import cn.edu.zut.soft.graduate.groupCenter.bo.GroupBO;
import cn.edu.zut.soft.graduate.groupCenter.bo.InviteBO;
import cn.edu.zut.soft.graduate.groupCenter.pojo.InviteInfo;
import cn.edu.zut.soft.graduate.massageCenter.bo.MessageBO;
import cn.edu.zut.soft.graduate.massageCenter.generator.Impl.InviteGroupBuilder;
import cn.edu.zut.soft.graduate.topicCenter.bo.GraduateStateService;
import cn.edu.zut.soft.graduate.userCenter.bo.IdentityBO;
import cn.edu.zut.soft.graduate.userCenter.bo.StudentBO;
import cn.edu.zut.soft.graduate.userCenter.handler.NoGroupHandler;
import cn.edu.zut.soft.graduate.userCenter.opjo.Invite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by chuchuang on 16/11/9.
 */
@Controller
@RequestMapping("/stu")
public class StudentController extends BaseController {

    @Resource
    private MessageBO messageBO;

    @Resource
    private GroupBO groupBO;

    @Resource
    private IdentityBO identityBO;

    @Resource
    private StudentBO studentBO;

    @Autowired
    private InviteBO inviteBO;

    @Resource
    private InviteGroupBuilder inviteGroupBuilder;

    @Resource
    private NoGroupHandler studentNoGroupHandler;

    @Resource
    private GraduateStateService graduateStateService;

    /**
     * 学生的默认首页
     *
     * @return
     */
    @RequestMapping
    public String index() {
        return "stu/index";
    }

    @RequestMapping("group")
    public String group() {
        return null;
    }

    /**
     * 学生的收件箱
     *
     * @param model
     * @param session
     * @param massageQuery
     * @return
     */
//    @RequestMapping("inbox")
//    public ModelAndView inbox(Map<String, Object> model, HttpSession session, MassageQuery massageQuery) {
//        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
//        Assert.notNull(loginVO);
//        massageQuery.setRecipients(loginVO.getId());
//        CommonResult<List<Message>> result = messageBO.findByQuery(massageQuery);
//        for (Message massage : result.getData()) {
//            massage.setContent(null);
//        }
//        model.put("list", JSON.toJSON(result.getData()));
//        model.put("count", result.getTotalCount());
//        model.put("pageSize", massageQuery.getLimit());
//        model.put("currentPage", massageQuery.getCurrentPage());
//        return new ModelAndView("usual/Inbox", model);
//    }

    /**
     * 学生的发件箱
     *
     * @param model
     * @param session
     * @param massageQuery
     * @return
     */
//    @RequestMapping("outbox")
//    public ModelAndView outbox(Map<String, Object> model, HttpSession session, MassageQuery massageQuery) {
//        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
//        Assert.notNull(loginVO);
//        massageQuery.setAddressor(loginVO.getId());
//        CommonResult<List<Message>> result = messageBO.findByQuery(massageQuery);
//        for (Message massage : result.getData()) {
//            massage.setContent(null);
//        }
//        model.put("list", JSON.toJSON(result.getData()));
//        model.put("count", result.getTotalCount());
//        model.put("pageSize", massageQuery.getLimit());
//        model.put("currentPage", massageQuery.getCurrentPage());
//        return new ModelAndView( "usual/Outbox",model);
//    }

    /**
     * 学生的个人信息页面
     *
     * @return
     */
    @RequestMapping("myself")
    public String studentInfo() {
        return "stu/stuInfo";
    }

    /**
     * 学生的小组页面
     *
     * @return
     */
    @RequestMapping("/stuGroup")
    public String tostuGroup() {
        return "/stu/stuGroup";
    }

    /**
     * 不存在的小组学生列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/noGroupList")
    public ModelAndView noGroupStudeng(HttpServletRequest request, Map<String, Object> model, IdentityQuery identityQuery) {
        LoginVO session = (LoginVO) request.getSession().getAttribute(IKEY.USER);
        Invite invite = new Invite();
        invite.setUser(session);
        invite.setRunner(Role.Runner.user);
        invite.setOwner(session.getId());

        identityQuery.setPageSize(Integer.MAX_VALUE);
        //修改角色为学生
        identityQuery.setRole(Role.stu);
        invite.setIdentityQuery(identityQuery);
        List<UserDescVO> result = identityBO.findCanInvitationUser(invite, studentNoGroupHandler);
        model.put("stuList", result);
        return new ModelAndView("/stu/noGroupList", model);
    }

    /**
     * 创建小组
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/creatGroup")
    public CommonResult createGroup(HttpSession session) {
        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
        CreateGroup createGroup = new CreateGroup();
        createGroup.setRole(Role.stu);
        createGroup.setOwner(loginVO.getId());
        createGroup.setUser(loginVO);
        createGroup.setRunner(Role.Runner.user);
        Group group = groupBO.userCreateGroup(createGroup);
        session.setAttribute(IKEY.GROUP_GROUP, group.getId());
        session.setAttribute(IKEY.GROUP_LEADER, group.getId());
        return CommonResult.successReturn(group);
    }

    /**
     * 邀请走的的消息发送,而不是实际的关联信息
     *
     * @param userId
     * @return
     */
    @RequestMapping("/invite")
    public ModelAndView invite(HttpSession session, @RequestParam("userId") Integer userId) {
        LoginVO loginVO = (LoginVO) session.getAttribute(IKEY.USER);
        try {
            InviteInfo inviteInfo = new InviteInfo().addLoginVO(loginVO).addPassivesWithId(userId).addGroupWithId(Integer.parseInt(session.getAttribute(IKEY.GROUP_GROUP).toString()));
            inviteBO.inviteOp(inviteInfo, InviteStatus.ING);
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("redirect:/stu/noGroupList");
        }
        return new ModelAndView("redirect:/stu/inviteSponsor");
    }

    /**
     * 功能描述:获取小组成员信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/groupInfo")
    public CommonResult groupInfoById(HttpServletRequest request) {
        LoginVO session = (LoginVO) request.getSession().getAttribute(IKEY.USER);
        List<UserDescVO> result = Collections.emptyList();
        Object group_group = request.getSession().getAttribute(IKEY.GROUP_GROUP);
        if (group_group == null) {
            return CommonResult.successReturn(result);
        }
        result = identityBO.findGroupMember(session, Integer.parseInt(group_group.toString()));
        return CommonResult.successReturn(result);
    }

    /**
     * 功能描述:删除小组
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deleteGroup")
    public CommonResult deleteGroup(HttpServletRequest request) {
        LoginVO session = (LoginVO) request.getSession().getAttribute(IKEY.USER);
        Object groupIdDelete = request.getSession().getAttribute(IKEY.GROUP_GROUP);
        Object groupLeader = request.getSession().getAttribute(IKEY.GROUP_LEADER);
        if (groupIdDelete == null) {
            return CommonResult.errorReturn("System error");
        }
        if (groupLeader == null) {
            return CommonResult.errorReturn("您不是小组长无权限操作!");
        }
        Group group = groupBO.delete(session, Integer.parseInt(groupIdDelete.toString()));
        request.getSession().setAttribute(IKEY.GROUP_GROUP, null);
        request.getSession().setAttribute(IKEY.GROUP_LEADER, "");
        return CommonResult.successReturn(group);
    }

    /**
     * 功能描述:邀请
     * @param groupId
     * @param model
     * @return
     */
    @RequestMapping("toInvitnte")
    public ModelAndView toInvitnte(@RequestParam("groupId") Integer groupId, Map<String, Object> model) {

        model.put("group", groupBO.get(groupId));

        return new ModelAndView("/usual/InviteMessageInfo", model);
    }

    @RequestMapping("notice")
    public String noticeDetails() {
        return "usual/notice";
    }

    /**
     * 功能描述:发件箱
     *
     * @return
     */
    @RequestMapping("/inviteSponsor")
    public ModelAndView inviteSponsor() {
        return new ModelAndView("/stu/inviteSponsor");
    }

    /**
     * 功能描述:收件箱
     *
     * @return
     */
    @RequestMapping("/inviteReceiver")
    public ModelAndView inviteReceiver() {
        return new ModelAndView("/stu/inviteReceiver");
    }

    @RequestMapping("/stuResults")
    public String stuResults(){
        return "/stu/stuResults";
    }

    /**
     * 毕业设计状态
     * @return
     */
    @RequestMapping("/graduateState")
    public String graduateState() {
        return "/stu/state";
    }

    /**
     * 查看中期抽取是否应用
     */
    @ResponseBody
    @RequestMapping("/stuDetectionMidRan")
    public CommonResult stuDetectionMidRan(){
        Boolean a = graduateStateService.detectionMidRan();
        if(a!=null){
            return CommonResult.successReturn(true);
        }else{
            return CommonResult.errorReturn("获取中期信息异常！！");
        }
    }
}
